
import HikCameraSDK from '@/utils/hikCamera';
import { post } from '@/utils/request';
import clsx from 'clsx';
import { message } from 'antd';

import './index.less'

export default function HikCameraPage() {
    const playerRef = useRef<any>(null);
    const [list, setList] = useState<any[]>([]);
    const [currentCode, setCurrentCode] = useState<string>('');
    const selectedCameraIndexRef = useRef<number>(0);

    useEffect(() => {
        // testNoProxyCameraRequest();
        fetchCameras();
        initVideoPlayer();
    }, []);


    async function testLocalProxyCameraRequest(cameraCode: string) {
        const hikCamera = HikCameraSDK.getInstance();
        const info = hikCamera.postSign({
            method: 'POST',
            url: '/artemis/api/video/v1/cameras/previewURLs',
        });
        console.log('/cameras/previewURLs info', info);

        const reqParam = {
            "cameraIndexCode": cameraCode,
            "streamType": 0,
            "protocol": "wss",
            "transmode": 1,
            "expand": "transcode=0"
        };

        const res = await post('/hik_camera/artemis/api/video/v1/cameras/previewURLs', reqParam, {
            dynamicBaseURL: '',
            headers: Object.fromEntries(info.headers),
        });

        let playUrl = '';

        if (res.code === '0') {
            playUrl = res.data.url;
        }
        return playUrl;
    }

    async function testNoProxyCameraRequest() {
        console.log('testCameraRequest');
        const hikCamera = HikCameraSDK.getInstance();
        const info = hikCamera.postSign({
            method: 'POST',
            url: '/artemis/api/video/v1/cameras/previewURLs',
        });
        console.log('info', info);

        const reqParam = {
            "cameraIndexCode": "9b85e532319a4d7aa8dd663e5eb102bb",
            "streamType": 0,
            "protocol": "wss",
            "transmode": 1,
            "expand": "transcode=0"
        };

        const res = await post('', reqParam, {
            dynamicBaseURL: info.url,
            headers: Object.fromEntries(info.headers),
        });

        console.log('testCameraRequest-res', res);

    }


    const initVideoPlayer = () => {
        const player = new window.JSPlugin({
            szId: 'play_window',//父窗口id，需要英文字母开头 必填
            szBasePath: "./",// 必填,与h5player.min.js的引用路径一致
            iMaxSplit: 4,
            iCurrentSplit: 2,
            openDebug: true,
            mseWorkerEnable: true,//是否开启多线程解码，分辨率大于1080P建议开启，否则可能卡顿
            bSupporDoubleClickFull: true,//是否支持双击全屏，true-双击是全屏；false-双击无响应
            oStyle: {
                borderSelect: '#FFCC00',
            }
        })

        playerRef.current = player;

        player.JS_SetWindowControlCallback({
            windowEventSelect: (iWndIndex: number) => {  //插件选中窗口回调
                selectedCameraIndexRef.current = iWndIndex;
            }
        });
    }

    const playVideo = async () => {
        const player = playerRef.current;
        if (!player) return;

        const videoUrl = await testLocalProxyCameraRequest(currentCode);


        if (!videoUrl) {
            message.error('海康平台-获取视频地址失败');
            return;
        }


        const targetIndex = selectedCameraIndexRef.current;

        player.JS_Play(videoUrl, {
            playUrl: videoUrl,
            mode: 0,
            keepDecoder: 0,
            token: ''
        }, targetIndex)
        player.JS_SelectWnd(targetIndex)
    }

    const stopPlayVideo = () => {
        const player = playerRef.current;
        if (!player) return;

        const targetIndex = selectedCameraIndexRef.current;
        player.JS_Stop(targetIndex);
    }

    const allFullScreen = () => {
        const player = playerRef.current;
        if (!player) return;

        player.JS_FullScreenDisplay(true);
    }

    const targetFullScreen = () => {
        const player = playerRef.current;
        if (!player) return;

        const targetIndex = selectedCameraIndexRef.current;

        player.JS_FullScreenSingle(targetIndex);
    }

    const fetchCameras = async () => {
        const hikCamera = HikCameraSDK.getInstance();
        const info = hikCamera.postSign({
            method: 'POST',
            url: '/artemis/api/resource/v1/cameras',
        });

        const reqData = {
            "pageNo": 1,
            "pageSize": 20,
            "treeCode": "0"
        }

        const res = await post('/hik_camera/artemis/api/resource/v1/cameras', reqData, {
            dynamicBaseURL: '',
            headers: Object.fromEntries(info.headers),
        });

        if (res.code === '0') {
            setList(res.data.list);
        } else {
            setList([]);
        }
    }

    return (
        <div className='test-camera-page'>
            <div className='title'>平安深汕-视频-API集成测试</div>

            <div className='content'>
                <div id="play_window"></div>
                <div className='camera-container'>
                    <div className='operator-container'>
                        <Button onClick={() => playVideo()} disabled={!currentCode}>预览视频</Button>
                        <Button onClick={() => stopPlayVideo()}>停止预览</Button>
                        <Button onClick={() => allFullScreen()}>整体全屏</Button>
                        <Button onClick={() => targetFullScreen()}>单窗口全屏</Button>
                    </div>
                    <div className='camera-list'>
                        {
                            list.map(item => {
                                const code = item.cameraIndexCode;
                                return (
                                    <div key={code}
                                        className={clsx('camera-item', { 'active': currentCode === code })}
                                        onClick={() => { setCurrentCode(code) }}>
                                        {item.name}
                                    </div>
                                )
                            })
                        }
                    </div>
                </div>

            </div>
        </div>
    )
}
